import 'package:bilibili/http/dao/home_dao.dart';
import 'package:bilibili/http/model/home_mo.dart';
import 'package:hi_common/util/color.dart';
import 'package:bilibili/util/toast.dart';
import 'package:bilibili/widget/hi_banner.dart';
import 'package:bilibili/widget/video_card.dart';
import 'package:flutter/material.dart' hide Banner;
import 'package:hi_net/http/core/hi_error.dart';

import '../http/model/banner_mo.dart';
import '../http/model/video_model.dart';

class HomeTabPage extends StatefulWidget {
  final String label;
  final List<BannerMo>? bannerList;

  const HomeTabPage({super.key, required this.label, this.bannerList});

  @override
  State<StatefulWidget> createState() {
    return _HomeTabPageState();
  }
}

class _HomeTabPageState extends State<HomeTabPage> {
  final List<VideoModel> _videoList = List.empty(growable: true);
  final ScrollController _scrollController = ScrollController();
  bool _isLoading = false;
  bool _isLastPage = false;

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_scrollListener);
    _loadData();
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      setState(() {
        _isLoading = true;
      });
      _loadData(loadMore: true);
    }
  }

  @override
  void dispose() {
    _scrollController.removeListener(_scrollListener);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
        onRefresh: _loadData,
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            if (widget.bannerList != null)
              SliverPadding(
                padding: const EdgeInsets.all(5),
                sliver: SliverToBoxAdapter(
                  child: HiBanner(widget.bannerList!.map((item) {
                    return item;
                  }).toList()),
                ),
              ),
            SliverPadding(
                padding: const EdgeInsets.only(left: 5, right: 5),
                sliver: SliverGrid(
                  gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 2),
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      if (index < _videoList.length) {
                        final item = _videoList[index];
                        return VideoCard(item);
                      }
                    },
                    childCount: _videoList.length + (_isLoading ? 1 : 0),
                  ),
                )),
            if (_isLoading)
              const SliverToBoxAdapter(
                child: Center(
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: CircularProgressIndicator(
                      color: primary,
                    ),
                  ),
                ),
              ),
            if (_isLastPage)
              const SliverToBoxAdapter(
                child: Center(
                  child: Padding(
                    padding: EdgeInsets.all(16),
                    child: Text("没有更多了！"),
                  ),
                ),
              ),
          ],
        ));
  }

  int _pageIndex = 1;

  Future<void> _loadData({bool loadMore = false}) async {
    try {
      if (loadMore) {
        if (!_isLastPage) {
          _pageIndex++;
        }
      } else {
        _isLastPage = false;
        _pageIndex = 1;
        _videoList.clear();
      }
      HomeMo data =
          await HomeDao.get(widget.label, pageIndex: _pageIndex, pageSize: 10);
      if (data.videoList != null) {
        if (!_isLastPage) {
          _videoList.addAll(data.videoList!);
        }
        if (data.videoList!.length < 10) {
          _isLastPage = true;
        } else {
          _isLastPage = false;
        }
      }

      setState(() {
        _isLoading = false;
      });
    } on NeedLogin catch (e) {
      showToast(e.message);
    } on HiNetError catch (e) {
      showToast(e.message);
    }
  }
}
